package com.duoketech.service.web.order;
import com.duoketech.config.Constant;
import com.duoketech.model.activity.Activity;
import com.duoketech.model.activityorder.ActivityOrder;
import com.duoketech.model.member.Member;
import com.duoketech.model.orderitem.OrderItem;
import com.duoketech.model.product.Product;
import com.duoketech.model.roomorder.RoomOrder;
import com.duoketech.service.AbstractService;
import com.duoketech.model.order.Order;
import com.duoketech.exception.ValidateException;
import com.duoketech.service.pay.IPAYCallBackFactory;
import com.duoketech.service.pay.IPayCallBack;
import com.duoketech.service.weixin.activity.WeiXinActivityService;
import com.duoketech.utils.PageUtil;
import com.duoketech.utils.WxMsgTemplateUtils;
import com.duoketech.utils.pay.weixin.required.WxPayUtil;
import com.duoketech.utils.search.EqualCondition;
import com.duoketech.utils.search.NotEqualCondition;
import com.duoketech.utils.search.QueryConstructor;
import com.duoketech.utils.validator.Validator;
import com.duoketech.utils.validator.rules.string.StringLengthBetween;
import com.duoketech.utils.validator.rules.string.StringMustBeMobile;
import com.duoketech.utils.validator.rules.string.StringMustBeRequired;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import javafx.beans.binding.Bindings;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;

public class OrderService extends AbstractService{
    public static OrderService ME = new OrderService();

    @Override
    public void validatorUpdate(Model<?> model, Kv kv) throws ValidateException {
        validatorAdd(model,kv);
    }

    @Override
    public void validatorAdd(Model<?> model, Kv kv) throws ValidateException {

        Validator validator = new Validator();
//        validator.addRule(new StringMustBeRequired(model.getStr(Order.ID),"项为必填信息"));
//        validator.addRule(new StringLengthBetween(model.getStr(Order.ID),"项字符必须为1-50个字符",1,50));
//        validator.addRule(new StringMustBeRequired(model.getStr(Order.ORDER_SER),"订单商品ID项为必填信息"));
//        validator.addRule(new StringLengthBetween(model.getStr(Order.ORDER_SER),"订单商品ID项字符必须为1-50个字符",1,50));
//        validator.addRule(new StringMustBeRequired(model.getStr(Order.OBJ_TYPE),"订单类型项为必填信息"));
//        validator.addRule(new StringLengthBetween(model.getStr(Order.OBJ_TYPE),"订单类型项字符必须为1-50个字符",1,50));
        validator.addRule(new StringMustBeRequired(model.getStr(Order.STATUS),"订单状态项为必填信息"));
        validator.addRule(new StringLengthBetween(model.getStr(Order.STATUS),"订单状态项字符必须为1-50个字符",1,50));
//        validator.addRule(new StringMustBeRequired(model.getStr(Order.CREATE_TIME),"创建时间项为必填信息"));
//        validator.addRule(new StringLengthBetween(model.getStr(Order.CREATE_TIME),"创建时间项字符必须为1-50个字符",1,50));
//        validator.addRule(new StringMustBeRequired(model.getStr(Order.MODIFY_TIME),"修改时间项为必填信息"));
//        validator.addRule(new StringLengthBetween(model.getStr(Order.MODIFY_TIME),"修改时间项字符必须为1-50个字符",1,50));
//        validator.addRule(new StringMustBeRequired(model.getStr(Order.TOTAL_FEE),"订单总价项为必填信息"));
//        validator.addRule(new StringLengthBetween(model.getStr(Order.TOTAL_FEE),"订单总价项字符必须为1-50个字符",1,50));
//        validator.addRule(new StringMustBeRequired(model.getStr(Order.CREATE_BY),"订单创建者项为必填信息"));
//        validator.addRule(new StringLengthBetween(model.getStr(Order.CREATE_BY),"订单创建者项字符必须为1-50个字符",1,50));
//        validator.addRule(new StringMustBeRequired(model.getStr(Order.UNIT_ID),"商家id项为必填信息"));
//        validator.addRule(new StringLengthBetween(model.getStr(Order.UNIT_ID),"商家id项字符必须为1-50个字符",1,50));
        validator.excute();

    }

    @Override
    public void beforAdd(Model<?> model, Kv kv) throws ValidateException {

    }

    @Override
    public void afterAdd(Model<?> model, Kv kv) throws ValidateException {

    }

    @Override
    public void beforUpdate(Model<?> model, Kv kv) throws ValidateException {

    }

    @Override
    public void afterUpdate(Model<?> model, Kv kv) throws ValidateException {

    }

    @Override
    public void beforQuery(int id, Model<?> model, Kv kv) throws ValidateException {

    }

    @Override
    public void afterQuery(int id, Model<?> model, Kv kv) throws ValidateException {

    }

    @Override
    public void beforDelete(int id, Model<?> model, Kv kv) throws ValidateException {

    }

    @Override
    public void afterDelete(int id, Model<?> model, Kv kv) throws ValidateException {

    }

    @Override
    public String tableName() {
        return Order.dao.tableName();
    }

    @Override
    public void builderSQLExpected(Model<?> model, QueryConstructor queryConstruct, Kv kv) {
        queryConstruct.and(new NotEqualCondition(Order.STATUS,Order.STATUS_DEL));
        queryConstruct.and(new EqualCondition(Order.UNIT_ID,999999));
        String value = model.getStr(Order.STATUS);
        if(StringUtils.isNotEmpty(value)){
            queryConstruct.and(new EqualCondition(Order.STATUS,value));
        }
    }

    public int doAddActivityOrder(ActivityOrder order) throws ValidateException {
        Validator validator = new Validator();


        String name = order.getStr(ActivityOrder.NAME);
        String mobile = order.getStr(ActivityOrder.MOBILE);
        int cardType = order.getInt(ActivityOrder.CARD_TYPE);
        String cardNo = order.getStr(ActivityOrder.CARD_NO);

        validator.addRule(new StringMustBeRequired(name,"请输入联系人姓名"));
        validator.addRule(new StringMustBeRequired(mobile,"请输入联系人电话"));
        validator.addRule(new StringMustBeMobile(mobile,"请输入正确的联系人电话"));
        validator.addRule(new StringMustBeRequired(cardType+"","请选择证件类型"));
        validator.addRule(new StringMustBeRequired(cardNo,"请输入证件号码"));

        validator.excute();

        //检查当前用户是否已经报名了当前活动

        int obj_id=order.getInt(ActivityOrder.OBJ_ID);
//        ActivityOrder temp = WeiXinActivityService.ME.queryActivityByCardNo(cardNo,obj_id);
//        if(temp!=null){
//            throw new ValidateException("你已经报名参加了当前活动了，请勿重复报名");
//        }
        int id = order.getInt(ActivityOrder.OBJ_ID);
        Activity activity = Activity.dao.findById(id);
        if(activity!=null){
            order.set(ActivityOrder.CREATE_TIME,new Date());
            order.set(ActivityOrder.STATUS,ActivityOrder.STATUS_NORMAL);
            order.set(ActivityOrder.PRICE,activity.getInt(Activity.PRICE));
            order.set(ActivityOrder.UNIT_ID,activity.getInt(Activity.CREATOR));
            order.set(ActivityOrder.ORDER_SN,System.currentTimeMillis()+"");
            order.save();

            //向预订者发送消息提醒
            int memberId = order.getInt(ActivityOrder.MEMBER_ID);
            Member member = Member.dao.findById(memberId);
            WxMsgTemplateUtils.sendBookSuccessMsg(member.getStr(Member.OPEN_ID),member.getStr(Member.NICK_NAME),activity.getStr(Activity.NAME));

            //向活动的创建者发送消息提醒
            member = Member.dao.findById(activity.getInt(Activity.CREATOR));
            WxMsgTemplateUtils.sendBookSuccessToOwnerMsg(member.getStr(Member.OPEN_ID),member.getStr(Member.NICK_NAME),
                    activity.getStr(Activity.NAME),order.getStr(ActivityOrder.NAME),order.getStr(ActivityOrder.MOBILE));

        }

        return order.getInt(ActivityOrder.ID);
    }



    public List<OrderItem> queryOrderItemByOrderId(int orderId){
        String sql="select t1.name,t2.* from "+Product.dao.tableName() +" t1, "+OrderItem.dao.tableName()+" t2 where t2.order_id=? and t2.product_id=t1.id and t2.status<>? order by t2.id desc";
        List<OrderItem> orderItems= OrderItem.dao.find(sql,orderId,OrderItem.STATUS_DEL);
        for(OrderItem o: orderItems){
            o.set(OrderItem.PRICE,PageUtil.fengToYuan(o.getInt(OrderItem.PRICE)));
            o.set(OrderItem.TOTAL_PRICE,PageUtil.fengToYuan(o.getInt(OrderItem.TOTAL_PRICE)));
            o.set(OrderItem.TOTAL_WEIGHT,PageUtil.g2Kg(o.getInt(OrderItem.TOTAL_WEIGHT)));
        }
        return orderItems;
    }


    public ActivityOrder queryActivityOrderById(int orderId){

        return ActivityOrder.dao.findById(orderId);
    }

    public RoomOrder queryRoomOrderById(int orderId){

        return RoomOrder.dao.findById(orderId);
    }

    public Order queryProductOrderById(int orderId){

        return Order.dao.findById(orderId);
    }


    public String doPayCallBack(String xml){

        String wexinXml = "";
        try {

            //记录下微信发过来的xml信息
            Map<String,String> result = WxPayUtil.xmlToMap(xml);
            String outTradeNo = result.get("out_trade_no");
            String transaction_id = result.get("transaction_id");
            String total_fee = result.get("total_fee");
            String[] temp = outTradeNo.split("_");
            String orderId = temp[0];
            String type = temp[1];
            String resultCode = result.get("result_code");
            String returnCode = result.get("return_code");
            String time_end = result.get("time_end");

            Record record = new Record();

            double fee = (Double.valueOf(total_fee))/100;

            record.set("msg",xml);
            record.set("pay_from","weixin");
            record.set("result_code",resultCode);
            record.set("total_fee",fee);
            record.set("order_id",orderId);
            record.set("trans_id",transaction_id);
            record.set("create_time",new Date());
            record.set("time_end",time_end);
            record.set("type",type);
            Db.save("t_payment_weixin",record);
            if(resultCode.equals("SUCCESS") && returnCode.equals("SUCCESS")){
                IPayCallBack callBack = IPAYCallBackFactory.create(type);
                callBack.doPayCallBack(Integer.valueOf(orderId));
//                Orders order = Orders.dao.findById(orderId);
//                if(order!=null && order.getInt(Orders.ORDERSTATUS)==Orders.STATUS_UNPAY){
//                    Member member = Member.dao.findById(order.getInt(Orders.MEMBER_ID));
//                    PayOrderSubject payOrderSubject = new PayOrderSubject();
//                    payOrderSubject.dispatchEvent(order,member);
//
//                    //通知微信服务器，已经成功接受到了这个订单的支付报文信息了
//                    StringBuffer sb = new StringBuffer("<xml>");
//                    sb.append("<return_code>SUCCESS</return_code>");
//                    sb.append("<return_msg>OK</return_msg>");
//                    sb.append("</xml>");
//                    wexinXml = sb.toString();
//                }
            }
        } catch (Exception e) {
            //通知微信服务器，已经成功接受到了这个订单的支付报文信息了
            StringBuffer sb = new StringBuffer("<xml>");
            sb.append("<return_code>ERROR</return_code>");
            sb.append("<return_msg>ERROR</return_msg>");
            sb.append("</xml>");
            wexinXml = sb.toString();
        }
        return wexinXml;
    }

}